<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class upload_library 
{
    var $_max_size = 204857600;
    var $_file_name = '';
    var $_base_upload_dir='';
    var $_upload_dir = '';
    var $_flag_file = 0;
    var $_file = NULL;
	
	function __construct()
	{
		$this->CI = get_instance();
	}
	
    public function configUpload($cfUpload)
	{
        if(isset($cfUpload['max_size']))
            $this->_max_size    = $cfUpload['max_size'];
        if(isset($cfUpload['new_file_name']))
            $this->_file_name   = $cfUpload['new_file_name'];
        if(isset($cfUpload['upload_dir']))
            $this->_upload_dir  = $cfUpload['upload_dir'];
        if(isset($cfUpload['base_upload_dir']))
            $this->_base_upload_dir  = $cfUpload['base_upload_dir'];
        if(isset($cfUpload['flag_file']))
            $this->_flag_file   = $cfUpload['flag_file'];
        if(isset($cfUpload['file']))
            $this->_file        = $cfUpload['file'];
    }
    function uploadFile()
    {
        //flag? 1 => images
        //		2 => video
        //		3 => file
        $data=array();
        $size=$this->_file['size'];
        
        if($size>$this->_max_size)
        {
            unlink($this->_file['tmp_name']);
            $data['err']="ERR_LA";
            $data['msg']="File vượt quá kích thước cho phép.";
            return $data;
        }
		$filename = strtolower(stripslashes($this->_file['name'])) ;
		$filename = (strlen($filename)>100) ? substr($filename, -80) : $filename ;       
        $extension = $this->get_file_extension($filename);
        
        if($this->_upload_dir=='')
		{
            $y_m_dir = $this->create_dir();
            $this->_upload_dir = $this->_base_upload_dir.$y_m_dir.'/';
        }
        switch ($this->_flag_file) {
            case '0':
                $ischeck=1;
                break;
            case '1':
                $ischeck = $this->isImage($extension);
                break;
            case '2':
                $ischeck = $this->isVideo($extension);	
                break;
            case '3':
                $ischeck = $this->isFile($extension);
                break;
            
        }
        if($ischeck==1)
		{
            $name_temp =str_replace( $extension ,'',$filename); 
            if($this->_file_name!='')
                $name = $this->_file_name.".".$extension;
            else
                $name = date("dmY_His")."_".rand(0,10000).'_'.$this->removeSign($name_temp).".".$extension;
            //$file_ext = $name.'.'.$extension;
            $dirfilename = $this->_upload_dir.$name;
            if (move_uploaded_file($this->_file['tmp_name'], $dirfilename))
            {
                $data['name']=$name;
                $data['old_name']=$name_temp;
                $arr_dir = explode('/',$this->_upload_dir);
            
                unset($arr_dir[0]);
                //$str_dir =  implode('/',$arr_dir);
                $data['str_dir']=$y_m_dir;
                if($this->isImage($extension)){
                    $data['type']="img";
                }elseif($this->isVideo($extension)||$this->isMusic($extension)){
                    $data['type']="vid";
                }else{
                    $data['type']="ort";
                }
                $data['ext']=$extension;
                $data['size']=$size;
                $data['err']="";
                $data['msg']="";
                return $data;
            }else{
                $data['err']="ERR_UL";
                $data['msg']="Lỗi trong quá trình upload file.";
                return $data;
            }
        }else{
            $data['err']="ERR_EX";
			if($this->_flag_file==1)
				$data['msg']="Ảnh upload không hợp lệ.\n Chỉ chấp nhận kiểu file: jpg|png|gif|jpeg";
			elseif($this->_flag_file==2)
				$data['msg']="Video upload không hợp lệ.\n Chỉ chấp nhận kiểu file: wmv|mpg|mp4|mov|avi|flv";
			elseif($this->_flag_file==3)
				$data['msg']="File upload không hợp lệ.\n Chỉ chấp nhận kiểu file: doc|zip|rar|docx|xlsx|pptx";
            return $data;
        }
    }
	function removeSign($str){
        $str = strip_tags($str);
        $str = mb_strtolower($str,'utf-8');
        $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);  //|á|à|ả|ã|ạ|ấ|ầ|ẩ|ẫ|ậ|ắ|ằ|ẳ|ẵ|ặ
        $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);  
        $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);  
        $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);  
        $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);  
        $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);  
        $str = preg_replace("/(đ)/", 'd', $str);
        $str = preg_replace("/(:|;)/","",$str);
        $str = preg_replace("/(́|̀|̉|̃|̣)/","",$str);
        $str = str_replace("_","",$str);
        $str = str_replace("?","",$str);
        $str = str_replace('"',"",$str); 
        $str = str_replace(")","",$str); 
        $str = str_replace("/","",$str);
        $str = str_replace("%","",$str);
        $str = str_replace("&","",$str);
        $str = str_replace("–","",$str);
        $str = str_replace("_","",$str);
        $str = str_replace(".","",$str);
        $str = str_replace(",","",$str);
        $str = str_replace("-","",$str);
        $str = str_replace("(","",$str);
        $str = str_replace("!","",$str); 
        $str = str_replace(" ","-",$str); 
        $str = str_replace("----","-",$str);
        $str = str_replace("---","-",$str);
        $str = str_replace("--","-",$str);
        $str = preg_replace(array('/[^a-zA-Z0-9 -]/'), array(''), $str) ;
        return $str; 
    }
	
    function toMBytes($bytes,$decimal=2) {
		$kb = ($bytes * 8) / 1024;
		$mb = ($kb /1024) / 8;
		return round($mb,$decimal);
	}
    
	function toKBytes($bytes,$decimal=2) {
		$kb = ($bytes * 1) / 1024;
		return round($kb,$decimal);
	}
    
    /*-----------------------------------------------------------------------*
    * Function: toBytes
    * Parameter: Mega bytes
    * Constants:  UPLOAD_SIZE_MBYTES | UPLOAD_SIZE_BYTES
    * Return: file size 
    *-----------------------------------------------------------------------*/

	function toBytes($mb) {
		$bytes = ((($mb * 8) * 1024) * 1024) / 8;
		return $bytes;
	}
	function isImage($str) {

		if(preg_match("/jpg|png|gif|jpeg/",$str)) return 1;
		return 0;
	}
	function isVideo($str) {

		if(preg_match("/wmv|mpg|mp4|mov|avi|flv/",$str)) return 1;
		return 0;
	}
	function isMusic($str) {
		if(preg_match("/wma|wav|mp3|asf/",$str)) return 1;
		return 0;
	}
	function isFile($str)
	{
		if(preg_match("/doc|zip|rar|docx|xlsx|pptx/",$str)) return 1;
		return 0;
	}
	
	/*function get_file_extension($file_name)
	{
		return substr(strrchr($file_name,'.'),1);
	}*/
	
	function get_file_extension($filename)
	{
		$path_info = pathinfo($filename); //trit($filename);
		return $path_info['extension'];
	}  
	
    function file_extension($filename)
	{
		$path_info = pathinfo($filename); 
		return $path_info['extension'];
	}
    function create_dir(){
        $y_m_dir = date('Y').'/'.date('m');
        if($this->_base_upload_dir!=''){
            $str_dir =$this->_base_upload_dir.$y_m_dir.'/'; 
            if(!is_dir($str_dir)){
                @mkdir($str_dir,0777, true);
            }
        }
        return $y_m_dir;
    }
}  

?>
